/**
 * Created by fengbo on 25/04/2017.
 */
"use strict";

const Env = use("Env");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");

const APP_KEY = Env.get("APP_KEY");

const CryptUtil = {
  jwtDecode(token) {
    if (token) {
      token = token.substr(0, 7) == "Bearer " ? token.substr(7) : token;
      try {
        let payload = jwt.verify(token, APP_KEY);
        // delete payload.exp
        // delete payload.iat
        return payload;
      } catch (err) {
        console.error("[JWT failed]", err);
        console.log("token", token);
        return null;
      }
    } else {
      return null;
    }
  },
  jwtEncodeInExpire(payload, second) {
    return jwt.sign(payload, APP_KEY, { expiresIn: second });
  },
  jwtEncode(payload, noExpire = true) {
    if (noExpire) {
      return jwt.sign(payload, APP_KEY);
    } else {
      return jwt.sign(payload, APP_KEY, { expiresIn: "3d" });
    }
  },

  md5(p_value) {
    return crypto.createHash("md5").update(p_value, "utf8").digest("hex");
  },
  wechatSign(sendObj, key) {
    let arr = [];
    for (let key in sendObj) {
      arr.push(key + "=" + sendObj[key]);
    }
    arr.sort((a, b) => (a > b ? 1 : -1));
    let str = `${arr.join("&")}&key=${key}`;
    let ret = this.md5(str).toUpperCase();
    return ret;
  },
  qimenSign(sendObj, body, secret = "") {
    let arr = [];
    for (let key in sendObj) {
      arr.push(key + sendObj[key]);
    }
    arr.sort((a, b) => (a > b ? 1 : -1));
    let str = `${secret}${arr.join("")}${body}${secret}`;
    let ret = this.md5(str).toUpperCase();
    console.log(str, ret);
    return ret;
  },
  OTMSSign(sendObj, secret = "") {
    let arr = [];
    for (let key in sendObj) {
      arr.push(key + sendObj[key]);
    }
    arr.sort((a, b) => (a > b ? 1 : -1));
    let str = `${secret}${arr.join("")}${secret}`;
    let ret = this.md5(str).toUpperCase();
    console.log(str, ret);
    return ret;
  },
  LBSQQSign(url, sendObj, secret = "") {
    let arr = [];
    for (let key in sendObj) {
      arr.push(key + "=" + sendObj[key]);
    }
    arr.sort((a, b) => (a > b ? 1 : -1));
    let str = `${url}?${arr.join("&")}${secret}`;
    let ret = this.md5(str).toUpperCase();
    console.log(str, ret);
    return ret.toLowerCase();
  },

  decryptData256(encryptedData, key) {
    encryptedData = new Buffer(encryptedData, "base64");
    var iv = "";
    let decipher = crypto.createDecipheriv(
      "aes-256-ecb",
      CryptUtil.md5(key),
      iv
    );
    decipher.setAutoPadding(true);
    let decoded = decipher.update(encryptedData, "base64", "utf8");
    decoded += decipher.final("utf8");
    return decoded;
  },
  encryptData256(data, key, iv = "") {
    // base64 decode
    key = Buffer.from(key, "binary");
    let clearEncoding = "utf8";
    let cipherEncoding = "base64";
    let cipherChunks = [];
    let cipher = crypto.createCipheriv("aes-256-ecb", key, iv);
    cipher.setAutoPadding(true);
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    return cipherChunks.join("");
  },
};

module.exports = CryptUtil;
